const path = require('path')

const resolve = file => path.resolve(__dirname, file)
const config = require(resolve('../config/env'))
const storeHtml = require('../server/storeHtml')
const requestXML = require('./sitemap-content')
// sitemap可访问路径
const sitemapKeys = [
  '/sitemap.xml',
  '/sitemap1.xml'
]
// 缓存页面
module.exports = async (req, res, next) => {
  // 设置强缓存
  let cacheKey = storeHtml.getCacheKey(req.path)
  /*解决缓存忽略参数的页面*/
  if (!cacheKey) {
    return await next()
  }

  if (cacheKey.includes('sitemap')) {
    res.setHeader('Content-Type', 'image/svg+xml')
  }

  try {
    let catchValue = storeHtml.getItem(cacheKey)
    if (catchValue) {
      let responseTime = Date.now() - req.xRequest.time // ms单位
      res.setHeader('X-Request-Id', req.xRequest.id + '-' + responseTime + '-0')
      res.setHeader('Cache-Control', 'public,max-age=' + config.cacheHtmlTime)
  
      res.send(catchValue);
      return
    } else {
      // js-ignore
      if (['www.zlketang.com'].includes(req.hostname) && sitemapKeys.includes(cacheKey)) {
        const data = await requestXML()
        if (data) {
          switch(cacheKey) {
            case '/sitemap.xml':
              return res.send(data[0])
            case '/sitemap1.xml':
              return res.send(data[1])
          }
        }
      }
    }
  } catch (e) {}

  next()
}
